import { boot } from "quasar/wrappers";
import { Loading } from "quasar";
import { useUserStore } from "src/stores/user";
import { usePermissionStore } from "src/stores/permission";
import useCommon from "src/composables/useCommon";
import { i18n } from "./i18n";

// LoadingBar.setDefaults({
//   color: "red",
//   size: "4px",
//   position: "top",
// });

function startLoading() {
  Loading.show({
    // spinner: QSpinnerGears,
    message: i18n.global.t("System") + i18n.global.t("onLoading"),
  });
  // LoadingBar.start();
}

function stopLoading() {
  Loading.hide();
  // LoadingBar.stop();
}

export default boot(({ router, store }) => {
  router.beforeEach((to, from, next) => {
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();
    // console.log(permissionStore.userMenu);
    startLoading();
    const token = userStore.GetToken();
    const { AllowList } = useCommon();

    //如果已登录
    if (token) {
      //且在白名单里
      if (AllowList.indexOf(to.path) !== -1) {
        //转向首页->Dashboard
        next({ path: "/" });
        stopLoading();
      }
      //不在白名单里
      else {
        //permissionStore里没有菜单数据就去请求菜单
        if (!permissionStore.userRouter.length) {
          permissionStore.GetUserMenu().then((res) => {
            //正常返回了
            if (res) {
              res.forEach((item) => {
                // 在vue-router4中，addRoutes被废弃，改为了addRoute，循环调用
                // 动态添加鉴权路由表
                router.addRoute(item);
              });

              //跳转至原来的请求
              next({ ...to, replace: true });
            }
            // 没有正常返回
            else {
              //注销，调用userStore的HandleLogout
              store.dispatch("user/HandleLogout");
              //跳转首页->login
              next({ path: "/", replace: true });
            }
          });
        }
        // permissionStore中有菜单数据
        else {
          // 直接跳转
          next();
        }
        stopLoading();
      }
    }
    // 如果没有登录
    else {
      // 在白名单里 直接跳转
      if (AllowList.indexOf(to.path) !== -1) {
        next();
        stopLoading();
      }
      // 不在白名单里 跳转至login
      else {
        next(`/login?redirect=${to.fullPath}`);
        stopLoading();
      }
    }
  });
  router.afterEach(() => {
    stopLoading();
  });
});
